import requests
import subprocess
import time
import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import sys
import winreg

# 配置文件路径
CONFIG_FILE = "campus_network_config.json"

# 默认配置
DEFAULT_CONFIG = {
    "SSID": "ZJKUNET",
    "LOGIN_URL": "http://10.255.254.250/a70.htm",
    "USERNAME": "",
    "PASSWORD": "",
    "REMEMBER": False,
    "AUTO_START": False  # 新增开机自启动配置
}

# 加载配置
def load_config():
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r') as f:
                return json.load(f)
        except:
            return DEFAULT_CONFIG
    return DEFAULT_CONFIG

# 保存配置
def save_config(config):
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f)

class CampusNetworkApp:
    def __init__(self, root):
        self.root = root
        self.root.title("校园网登录工具")
        self.root.geometry("500x380")  # 增加高度以容纳新控件
        self.root.resizable(False, False)
        
        # 加载配置
        self.config = load_config()
        
        # 创建UI元素
        self.create_widgets()
        
        # 加载保存的配置
        self.load_saved_config()
        
        # 检查是否需要自动启动
        if self.config.get("AUTO_START", False):
            self.auto_login()

    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="校园网登录工具", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # WLAN名称
        ttk.Label(main_frame, text="WLAN名称:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.ssid_var = tk.StringVar(value=DEFAULT_CONFIG["SSID"])
        self.ssid_entry = ttk.Entry(main_frame, textvariable=self.ssid_var, width=30)
        self.ssid_entry.grid(row=1, column=1, sticky=tk.W, pady=5)
        
        # 登录地址
        ttk.Label(main_frame, text="登录地址:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.url_var = tk.StringVar(value=DEFAULT_CONFIG["LOGIN_URL"])
        self.url_entry = ttk.Entry(main_frame, textvariable=self.url_var, width=30)
        self.url_entry.grid(row=2, column=1, sticky=tk.W, pady=5)
        
        # 用户名
        ttk.Label(main_frame, text="用户名:").grid(row=3, column=0, sticky=tk.W, pady=5)
        self.username_var = tk.StringVar()
        self.username_entry = ttk.Entry(main_frame, textvariable=self.username_var, width=30)
        self.username_entry.grid(row=3, column=1, sticky=tk.W, pady=5)
        
        # 密码
        ttk.Label(main_frame, text="密码:").grid(row=4, column=0, sticky=tk.W, pady=5)
        self.password_var = tk.StringVar()
        self.password_entry = ttk.Entry(main_frame, textvariable=self.password_var, show="*", width=30)
        self.password_entry.grid(row=4, column=1, sticky=tk.W, pady=5)
        
        # 记住密码
        self.remember_var = tk.BooleanVar(value=False)
        self.remember_check = ttk.Checkbutton(
            main_frame, text="记住密码", variable=self.remember_var,
            command=self.toggle_remember
        )
        self.remember_check.grid(row=5, column=0, columnspan=2, sticky=tk.W, pady=5)
        
        # 开机自动启动并连接
        self.auto_start_var = tk.BooleanVar(value=False)
        self.auto_start_check = ttk.Checkbutton(
            main_frame, text="开机自动启动并连接", variable=self.auto_start_var,
            command=self.toggle_auto_start
        )
        self.auto_start_check.grid(row=6, column=0, columnspan=2, sticky=tk.W, pady=5)
        
        # 登录按钮
        self.login_button = ttk.Button(
            main_frame, text="登录", command=self.login,
            style="Accent.TButton"
        )
        self.login_button.grid(row=7, column=0, columnspan=2, pady=10)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        self.status_bar = ttk.Label(
            main_frame, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W
        )
        self.status_bar.grid(row=8, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(10, 0))

    def load_saved_config(self):
        """加载保存的配置"""
        if self.config.get("REMEMBER", False):
            self.username_var.set(self.config.get("USERNAME", ""))
            self.password_var.set(self.config.get("PASSWORD", ""))
            self.remember_var.set(True)
        
        # 加载WLAN名称和登录地址
        self.ssid_var.set(self.config.get("SSID", DEFAULT_CONFIG["SSID"]))
        self.url_var.set(self.config.get("LOGIN_URL", DEFAULT_CONFIG["LOGIN_URL"]))
        
        # 加载开机自启动设置
        self.auto_start_var.set(self.config.get("AUTO_START", False))

    def toggle_remember(self):
        """切换记住密码状态"""
        if not self.remember_var.get():
            # 清除保存的密码
            self.config["PASSWORD"] = ""
            self.config["USERNAME"] = ""
            self.config["REMEMBER"] = False
            save_config(self.config)

    def toggle_auto_start(self):
        """切换开机自启动状态"""
        self.config["AUTO_START"] = self.auto_start_var.get()
        save_config(self.config)
        
        # 设置或取消开机自启动
        self.set_auto_start(self.auto_start_var.get())

    def set_auto_start(self, enable):
        """设置或取消开机自启动"""
        key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)
            if enable:
                # 获取当前程序的完整路径
                exe_path = sys.executable
                # 构造启动命令
                command = f'"{exe_path}"'
                winreg.SetValueEx(key, "CampusNetworkAutoLogin", 0, winreg.REG_SZ, command)
            else:
                try:
                    winreg.DeleteValue(key, "CampusNetworkAutoLogin")
                except FileNotFoundError:
                    pass
            winreg.CloseKey(key)
        except Exception as e:
            messagebox.showerror("错误", f"设置开机自启动失败: {str(e)}")

    def auto_login(self):
        """自动登录（用于开机自启动）"""
        # 检查是否保存了用户名和密码
        if not self.config.get("REMEMBER", False) or not self.config.get("USERNAME") or not self.config.get("PASSWORD"):
            self.status_var.set("自动登录失败：未保存用户名或密码")
            return
        
        # 执行登录
        self.login(auto_login=True)

    def login(self, auto_login=False):
        """执行登录操作"""
        # 获取输入值
        ssid = self.ssid_var.get().strip()
        login_url = self.url_var.get().strip()
        username = self.username_var.get().strip()
        password = self.password_var.get().strip()
        
        # 验证输入
        if not ssid:
            if auto_login:
                self.status_var.set("自动登录失败：未设置WLAN名称")
                return
            messagebox.showerror("错误", "请输入WLAN名称")
            return
        if not login_url:
            if auto_login:
                self.status_var.set("自动登录失败：未设置登录地址")
                return
            messagebox.showerror("错误", "请输入登录地址")
            return
        if not username:
            if auto_login:
                self.status_var.set("自动登录失败：未保存用户名")
                return
            messagebox.showerror("错误", "请输入用户名")
            return
        if not password:
            if auto_login:
                self.status_var.set("自动登录失败：未保存密码")
                return
            messagebox.showerror("错误", "请输入密码")
            return
        
        # 更新状态
        self.status_var.set("正在连接WLAN...")
        self.root.update()
        
        try:
            # 连接WLAN
            subprocess.run(
                ["netsh", "wlan", "connect", f"name={ssid}"],
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding="utf-8"
            )
            time.sleep(5)  # 等待连接建立
            
            # 更新状态
            self.status_var.set("正在登录...")
            self.root.update()
            
            # 准备登录数据
            data = {
                "DDDDD": username,
                "upass": password,
                "R1": "0", 
                "R3": "0", 
                "R6": "0",
                "para": "00",
                "0MKKey": "123456", 
                "buttonClicked": "",
                "redirecturl": "",
                "errflag": "",
                "username": "",
                "password": "",
                "user": "",
                "cmd": "",
                "Login": "", 
                "v6ip": ""
            }
            
            # 发送登录请求
            session = requests.Session()
            response = session.post(login_url, data=data)
            
            # 检查登录结果
            if "认证成功页" in response.text or f"UID='{username}'" in response.text:
                self.status_var.set("登录成功,关闭网页即可")
                if not auto_login:
                    messagebox.showinfo("成功", "登录成功！关闭网页即可！")
                
                # 保存配置
                if self.remember_var.get():
                    self.config["USERNAME"] = username
                    self.config["PASSWORD"] = password
                    self.config["REMEMBER"] = True
                else:
                    self.config["USERNAME"] = ""
                    self.config["PASSWORD"] = ""
                    self.config["REMEMBER"] = False
                
                # 保存WLAN名称和登录地址
                self.config["SSID"] = ssid
                self.config["LOGIN_URL"] = login_url
                
                save_config(self.config)
                
                # 显示用户信息
                try:
                    user_info_start = response.text.find("UID'")
                    if user_info_start != -1:
                        user_info_end = response.text.find("'", user_info_start + 5)
                        user_info = response.text[user_info_start:user_info_end + 1]
                        if not auto_login:
                            messagebox.showinfo("用户信息", f"用户信息: {user_info}")
                except Exception as e:
                    print(f"解析用户信息时出错: {e}")
            else:
                self.status_var.set("登录失败")
                if not auto_login:
                    messagebox.showerror(
                        "登录失败", 
                        f"登录失败，请检查参数。\n\n响应内容:\n{response.text[:500]}..."
                    )
        except subprocess.CalledProcessError as e:
            self.status_var.set("WLAN连接失败")
            if not auto_login:
                messagebox.showerror("错误", f"连接WLAN失败: {e.stderr}")
        except Exception as e:
            self.status_var.set("发生错误")
            if not auto_login:
                messagebox.showerror("错误", f"发生错误: {str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = CampusNetworkApp(root)
    root.mainloop()
